<?php


namespace app\db\admin;

use app\table\CmsTable;
use yifang\db\Db_raw;

class D_adminRole
{

    /** 直接使用sql时使用,带表前缀
     * @return string
     */
    private function getTableName(): string
    {
        return CmsTable::member_admin_role();
    }

    /**
     * 获取数据详情
     * @param string $paramObj
     */
    public function info($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $rules = array(
                'id' => 'require',
                'field' => '',
                'verify' => '',
            );
            $dataDefault["verify"] = 1;
            $dataDefault["field"] = "*";
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = getValidateMessage($rules);
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            $condition = array();
            $condition[] = array(
                "id", "=", $dataObj->request->id
            );
            try {
                $result = Db()->name(CmsTable::member_admin_role())->where($condition)->find();
                if ($dataObj->request->verify) {
                    if (empty($result)) {
                        $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, app("errorCode")::DATA_NOT_EXIST, lang("sys.dataNotExists"));
                    }
                }
                if ($final_arr["error_no"] == 0 && $result) {
                    $final_arr["result"] = $result;
                }
            } catch (\Throwable $e) {
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**取多个角色信息
     * @param $paramObj
     * @return array
     */
    public function idsInfo($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化
        //校验数据合法
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0); //获取是否混合数据 1混合 0 只用默认
            $params = parseToArr($paramObj, "params", array());//  参数

            $rules = getKeyDefaultRule(array(           //设置规则 如果为空就用默认规则
                'ids' => 'array',
                'field' => '',
                'verify' => '',
            ));
            $dataDefault["verify"] = 1;
            $messages = getValidateMessage($rules); //验证规则提示  继承客户端的消息信息
            $dataDefault = array();
            $dataDefault["field"] = "*";

            $paramsObj = paramsObj();  //新建一个空对象
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;

            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }


        //执行数据操作
        if ($final_arr["error_no"] == 0) {
            $where[] = array(
                "id", "IN", $dataObj->request->ids
            );

            try {
                $result = Db()->name(CmsTable::member_admin_role())->field($dataObj->request->field)->where($where)->select();
                if (count($result) == 0 && $dataObj->request->verify) {
                    $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_NOTICE, app("errorCode")::DATA_NOT_EXIST, "数据不存在");
                } else {
                    $final_arr["result"] = $result; //返回信息放入结果
                }
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**添加角色信息
     * @param $paramObj
     * @return array
     */
    public function store($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化
        //校验数据合法
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0); //获取是否混合数据 1混合 0 只用默认
            $params = parseToArr($paramObj, "params", array());//  参数

            $rules = getKeyDefaultRule(array(           //设置规则 如果为空就用默认规则
                'name' => 'require|max:50',
                'description' => 'must|max:200',
                'status' => '',
            ));
            $messages = getValidateMessage($rules); //验证规则提示  继承客户端的消息信息
            $dataDefault = array(
                'name' => '',
                'description' => '',
                'status' => 1,
            );


            $paramsObj = paramsObj();  //新建一个空对象
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;

            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //执行数据操作
        if ($final_arr["error_no"] == 0) {
            $where = array();
            $data = array(
                "name" => $dataObj->request->name,
                "description" => $dataObj->request->description,
                "status" => $dataObj->request->status,
            );

            try {
                $result = Db()->name(CmsTable::member_admin_role())->insert($data);
                $final_arr["result"] = $result; //返回信息放入结果
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**
     * 更新数据
     * @param string $paramObj
     */
    public function update($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $rules = array(
                'id' => 'require|number',
                'name' => '',
                'description' => '',
                'status' => '',
                'verify' => '',
            );
            $dataDefault = array();
            $dataDefault["verify"] = 1;
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = getValidateMessage($rules);
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            if ($dataObj->request->verify) {
                $paramsObj = paramsObj();
                $paramsObj->params = array(
                    "id" => $dataObj->request->id,
                    "verify" => 1,
                );
                $checkResult = $this->info($paramsObj);
                if ($checkResult["error_no"] == 0) {

                } else {
                    $final_arr = logCallErrorMsg($final_arr, $checkResult);
                }
            }
        }

        if ($final_arr["error_no"] == 0) {
            $condition = array();
            $condition[] = array(
                "id", "=", $dataObj->request->id
            );
            $data = array();
            $allowUpdates = ["name", "description", "status"]; //允许更新的字段
            foreach ($dataObj->request as $key => $value) {
                if (in_array($key, $allowUpdates) && $value !== null) {
                    $data[$key] = $value;
                }
            }
            if ($data) {
                try {
                    $result = Db()->name(CmsTable::member_admin_role())->where($condition)->data($data)->update();
                    $return = array();
                    $return["id"] = $dataObj->request->id;
                    $return["affected_rows"] = $result["affected_rows"];
                    $final_arr["result"] = $return;
                } catch (\Throwable $e) {
                    $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
                }
            } else {
                $return = array();
                $return["id"] = $dataObj->request->id;
                $return["affected_rows"] = 0;
                $final_arr["result"] = $return;
            }
        }
        return $final_arr;
    }

    /**批量删除
     * @param $paramObj
     * @return array
     */
    public function delete($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求 校验后的数据,包括默认值都会放这里
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化
        //校验数据合法
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0); //获取是否混合数据 1混合 0 只用默认
            $params = parseToArr($paramObj, "params", array());//  参数

            $rules = getKeyDefaultRule(array(           //设置规则 如果为空就用默认规则
                'id' => 'require',
            ));
            $messages = getValidateMessage($rules); //验证规则提示  继承客户端的消息信息
            $dataDefault = array();

            $paramsObj = paramsObj();  //新建一个空对象
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;

            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //执行数据操作
        if ($final_arr["error_no"] == 0) {
            //判断 id是否为数组,如果是数组,返回id数组,如果不是数组,返回单成员数组
            $ids = is_array($dataObj->request->id) ? $dataObj->request->id : explode(",", $dataObj->request->id);
            $where[] = array(
                "id", "IN", $ids
            );

            try {
                $result = Db()->name(CmsTable::member_admin_role())->where($where)->delete();
                $final_arr["result"] = $result; //返回信息放入结果
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }


    /**
     * 列表数据
     * @param string $paramObj
     */
    public function listData($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = array();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                "type" => "",
                "keyword" => "",
                "status" => "",
                "order" => "",
                'field' => '',
            );
            $dataDefault = array(
                'order' => '1',
            );
            $dataDefault["field"] = "*";
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            $condition = array();
            if ($dataObj->request->keyword) {
                switch ($dataObj->request->type) {
                    case 0:     //搜索角色名
                        $raw=new Db_raw();
                        $raw->setContent("LOCATE('{$dataObj->request->keyword}',`name`)");
                        $condition[] = array(
                            $raw, ">", 0
                        );
                        break;
                }
            }
            if ($dataObj->request->status > 0) {
                $condition[] = array(
                    "status", "=", $dataObj->request->status
                );
            }
            //处理 排序  设置默认0
            $sortColumn = "id";
            $sortDirection = $dataObj->request->order % 2 === 1 ? "ASC" : "DESC";   //单数升序 双数降序 0也为降序

            switch ($dataObj->request->order) {
                case 1:
                case 2:  // id 升序
                    $sortColumn = "id";
                    break;
            }
            try {
                $result = Db()->name(app("cmsTable")::member_admin_role())->order($sortColumn, $sortDirection)->field($dataObj->request->field)->where($condition)->paginate();
                $final_arr["result"] = $result;
            } catch (\Throwable $e) {
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**取分页总数
     * @param $paramObj
     * @return array
     */
    public function getCount($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化
        //校验数据合法
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0); //获取是否混合数据 1混合 0 只用默认
            $params = parseToArr($paramObj, "params", array());//  参数

            $rules = getKeyDefaultRule(array(           //设置规则 如果为空就用默认规则
                "type" => "",
                "keyword" => "",
                "status" => ""
            ));
            $messages = getValidateMessage($rules); //验证规则提示  继承客户端的消息信息
            $dataDefault = array(
                "type" => 1,
                "keyword" => "",
                "status" => -1
            );

            $paramsObj = paramsObj();  //新建一个空对象
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;

            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //执行数据操作
        if ($final_arr["error_no"] == 0) {
            $request = $dataObj->request;
            $tableName = $this->getTableName();
            $sql = "SELECT count(*) as count  FROM $tableName";
            $where = [];
            //处理条件

            if ($request->status > 0) {
                $where[] = "status=$request->status";
            }

            if ($request->keyword && $request->type > 0) {
                switch ($dataObj->request->type) {
                    case 1:     //搜索角色名
                        $where[] = "name like ? ";
                        $bind[] = "%$request->keyword%";
                        break;
                    case 2:     //搜索描述
                        $where[] = "description like ? ";
                        $bind[] = "%$request->keyword%";
                        break;
                }
            }

            //处理条件
            if (count($where) > 0) {
                $sql .= " WHERE ";
                $sql .= implode(" AND ", $where);
            }

            try {
                $result = Db()->query_sql($sql,$bind);
                $final_arr["result"] = $result[0]; //返回信息放入结果
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**取全部角色信息
     * @param $paramObj
     * @$all $paramObj
     * @return array
     */
    public function getAll($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化

        //执行数据操作
        if ($final_arr["error_no"] == 0) {
            try {
                $result = Db()->name(CmsTable::member_admin_role())->select();
                $final_arr["result"] = $result; //返回信息放入结果
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }
}